package com.example.bluetooth_test;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.ExtractedTextRequest;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public class MainActivity extends AppCompatActivity {

    BluetoothAdapter bluetoothAdapter;
    ListView bondedDevices, otherDevices;
    Button btScan;
    TextView btStatus;

    private  ClientThread mClientThread;
//    private Handler mhandler = null;
//    private MyAPP myAPP = null;

//    public static final String maction = "com.example.message.BroadcastAction";
    //listView 显示数据需要三部分：ArrayAdapter适配器，List<String>列表，ListView控件
    ArrayAdapter<String> bondedarrayAdapter, otherarrayAdapter;
    List<BluetoothDevice> motherDevices = new ArrayList<BluetoothDevice>();
    List<BluetoothDevice> mbondedDevices = new ArrayList<BluetoothDevice>();
    ArrayList<String> bondedArrayList = new ArrayList<String>();
    ArrayList<String> otherArrayList = new ArrayList<String>();

    private static final int ACTION_REQUEST_OK = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    @SuppressLint("ObsoleteSdkInt")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        myAPP = (MyAPP)getApplication();
//        mhandler = myAPP.getHandler();

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        btScan = findViewById(R.id.scan);
        bondedDevices = findViewById(R.id.bondedDevices);
        otherDevices = findViewById(R.id.otherDevices);
        btStatus = findViewById(R.id.status);



        if (!bluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, ACTION_REQUEST_OK);
        }

        //设置定位权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }

        registerBluetoothReceiver();
        bondedarrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, bondedArrayList);
        otherarrayAdapter =new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, otherArrayList);
        bondedDevices.setAdapter(bondedarrayAdapter);
        otherDevices.setAdapter(otherarrayAdapter);

//        otherDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @TargetApi(Build.VERSION_CODES.KITKAT)
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
//                BluetoothDevice device = motherDevices.get(i);
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
//                {
//                    device.createBond();
//                }

//            }
//        });
        otherDevices.setOnItemClickListener(moListClickListener);
        bondedDevices.setOnItemClickListener(mbListClickListener);
        btScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                bluetoothAdapter.startDiscovery();
            }
        });
    }

    private AdapterView.OnItemClickListener moListClickListener = new AdapterView.OnItemClickListener() {
        @SuppressLint("ObsoleteSdkInt")
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
            BluetoothDevice device = motherDevices.get(i);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){

                device.createBond();
            }
        }
    };

    private AdapterView.OnItemClickListener mbListClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
            BluetoothDevice device = mbondedDevices.get(i);
            if (mClientThread != null) {
                mClientThread.cancle();
            }
            mClientThread = new ClientThread(device, handler);
            mClientThread.start();

            btStatus.setText("Connecting");


        }
    };

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {


            switch (msg.what) {
                case Constant.STATE_CONNECTING:
                    btStatus.setText("Connecting");
                    break;
                case Constant.STATE_CONNECTED:
                    btStatus.setText("Connected");
                    Intent intent = new Intent(MainActivity.this, Control.class);
                    Control.mClientThread = mClientThread;
                    startActivity(intent);
                    break;
                case Constant.STATE_CONNECTION_FAILED:
                    btStatus.setText("Connection Failed");
                    break;
                case Constant.STATE_MESSAGE_RECEIVED:
                    byte[] readBuffer = (byte[]) msg.obj;
                    String tempMsg = new String(readBuffer, 0, msg.arg1);
//                  Message mmsg = Control.mHandler.obtainMessage(Constant.STATE_MESSAGE_RECEIVED, handler);
                    Control.mesText.setText(tempMsg);
//
            }
            return true;
        }
    });

        private void registerBluetoothReceiver() {

        IntentFilter filter = new IntentFilter();
        //添加广播所拥有的行动
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
//        filter.addAction(Control.TURN_UP);
//        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        //注册广播
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();

        if (mClientThread != null) {
            mClientThread.cancle();
        }
    }

    //设置广播接收器，监听广播搜索结果
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                Toast.makeText(getApplicationContext(), "Searching is begining", Toast.LENGTH_SHORT).show();
                bondedArrayList.clear();
                otherArrayList.clear();
                bondedarrayAdapter.notifyDataSetChanged();
                otherarrayAdapter.notifyDataSetChanged();
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    bondedArrayList.add(device.getName() + "@" + device.getAddress());
                    mbondedDevices.add(device);
                    bondedarrayAdapter.notifyDataSetChanged();
                } else {
                    motherDevices.add(device);
                    otherArrayList.add(device.getName() + "@" + device.getAddress());
                    //通知adapter调用getview刷新item
                    otherarrayAdapter.notifyDataSetChanged();
                }
            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Toast.makeText(getApplicationContext(), "Searching is over", Toast.LENGTH_SHORT).show();
            }
//            else if (Control.TURN_UP.equals(action)) {
//                String turnUp = intent.getStringExtra("turnup");
//                mClientThread.write(turnUp.getBytes());
//            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ACTION_REQUEST_OK) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(getApplicationContext(), "Bluetooth is enable", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Bluetooth enabling cancled", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
